// mdda.cpp
// multi dimensional dynamic array

#include "auxlib.h"
#include <iostream>
using namespace std;
#include "mdda.h"

double **allocMatrixMdda(int r, int c) 
{
	double **ret;
	ret = new double* [r];
	for (int i=0 ; i < r ; i++)
		ret[i] = new double [c];
	return ret;

/*
	double **ret;
	ret = new double* [c];
	for (int i=0 ; i < c ; i++)
		ret[i] = new double [r];
	return ret;
*/
}

void fillMatrixMdda(double **p, int r, int c, double d) 
{
	for (int i=0 ; i < r ; i++) {
		for (int j=0 ; j < c ; j++) {
			p[i][j] = d;
		}
	}
}

void addToMatrixMdda(double **p, int r, int c, double d) 
{
	for (int i=0 ; i < r ; i++) {
		for (int j=0 ; j < c ; j++) {
			p[i][j] += d;
		}
	}
}

void deleteMatrixMdda(double **p, int r) 
{
	for (int i=0 ; i < r ; i++)
		delete [] p[i];
	delete [] p;
}

void multidimensional_dynamic_array(int size) 
{
	cout << "=== multidimensional_dynamic_array, size=" << size << endl;
	double eps = 1e-8;
	MyClock clk;
	double duration_sec;
	clk.markTime();
	// code to test begin (1)
	int row = size, col = size;
	double **p = allocMatrixMdda(row,col);
	fillMatrixMdda(p,row,col,1.1);
	duration_sec = clk.getDiffTime();
	cout << "alloc & fill matrix=" << duration_sec << " sec" << endl;
	// code to test begin (2)
	clk.markTime();
	addToMatrixMdda(p,row,col,2.2);
	duration_sec = clk.getDiffTime();
	cout << "addToMatrix=" << duration_sec << " sec" << endl;
	// code to test end (2)

	// confirm that add was done
	myAssert(nearEqual(p[2][3],3.3,eps));

	// code to test begin (3)
	clk.markTime();
	deleteMatrixMdda(p,row);
	duration_sec = clk.getDiffTime();
	cout << "deleteMatrix=" << duration_sec << " sec" << endl;
	// code to test end (3)
}
